//
//  StatusCellPictureView.swift
//  HMWeibo
//
//  Created by wulei on 15/12/12.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
import SDWebImage
private let StatusPictureViewItemMargin: CGFloat = 8

// 可重用CellID
private let StatusPictureCellID = "StatusPictureCellID"
class StatusCellPictureView: UICollectionView {
    
    // MARK: - 视图模型
    var ViewModel: HMStatusViewModel? {
        
        didSet{
            // 当你想使用最合适空间的大小,来调整当前视图
            // 如果你想改变视图默认大小信息,就重写 sizeThatFits: 此方法
            sizeToFit()
            reloadData()
        }
    }
    
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateViewSzie()
    }
    
    // MARK: - 构造函数

    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        // 设置间距: - 默认的 itemSize 的大小: 50 * 50
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        // 数据源: 自己当自己的数据源
        // 应用场景: 自定义视图的小框架
        
        dataSource = self
        delegate = self
        
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellID)
        
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - 数据源方法
extension StatusCellPictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    // 选中图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        imageViewForPresent(indexPath)
//        photoBrowserPresonFromRect(indexPath)
//        photoBrowserPresonToRect(indexPath)
        
        let userInfo = [WBStatusSelecetedPhotoIndexPathKey: indexPath,
            WBStatusSelecetedPhotoURLsKey: ViewModel!.thumbnailUrls!]
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelecetedPhotoNotification, object: self, userInfo: userInfo)
        
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return ViewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView .dequeueReusableCellWithReuseIdentifier(StatusPictureCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.backgroundColor = UIColor.redColor()
        cell.imageURL = ViewModel?.thumbnailUrls![indexPath.item]
        
        return cell
    }
    
    
}
// MARK: - 自定义Cell
private class StatusPictureViewCell: UICollectionViewCell {
    
    private var imageURL:NSURL? {
        
        didSet{
            // 底层OC框架,可/必选项不严格
            // SD 超时长15S, 一旦超时会进入黑名单
             // 如果 URL 不变,图像也会更新
            
            iconView.sd_setImageWithURL(imageURL, placeholderImage: nil,
                options: [SDWebImageOptions.RetryFailed,
                    SDWebImageOptions.RefreshCached])
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        contentView .addSubview(iconView)
        
        // 设置布局- 因为Cell 会变化,不同的 cell 大小可能会变
//        iconView.frame = bounds
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
    }
    
    
    //  懒加载UIImageVIew
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    
}

// MARK: - 计算视图大小
extension StatusCellPictureView {
    private func calculateViewSzie() -> CGSize {
        
        // 获取图片数量
        let count =  ViewModel?.thumbnailUrls?.count ?? 0
        
        
        
        let colCount: CGFloat = 3
        let maxWidth = UIScreen.mainScreen().bounds.size.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - StatusPictureViewItemMargin * (colCount - 1 )) / colCount
        
        
        // 设置Layout itemSize 的大小
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        if count == 0 {
            return CGSizeZero
        }
        

        if count == 1 {
            
            var itemSize =  CGSize(width: 150, height: 120)
            
            
            // 用SDWebImage 检查本地缓存图像 - key 就是URL 的完整字符串
            // SDWedImage 是如何来缓存图片名 - 完整的URL 字符串 -> "MD5"
            if let URL = ViewModel?.thumbnailUrls?.first?.absoluteString {
                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(URL){
                    
                    itemSize =  image.size
                }
            }
            
            // 图片过小处理
            itemSize.width = itemSize.width < 40 ? 10 : itemSize.width
            
            
            // 图片过大处理
            if  itemSize.width > 300 {
                let w: CGFloat = 300
                let h = (w * itemSize.height) / itemSize.width
                itemSize = CGSize(width: w, height: h)
            }
            layout.itemSize = itemSize
            
            
            
            return itemSize
        }
        
        // 4张图片按照 2 * 2 来显示
        if count == 4 {
            let W = 2 * itemWidth + StatusPictureViewItemMargin
            
            
            
            return CGSize(width: W, height: W)
        }
        
        /*
        2 3
        5 6
        7 8 9
        
        
        */
        // 其它图片按照 九宫格来显示
        let rowNum = CGFloat(Int((count - 1 ) / Int(colCount) + 1))
        let H = itemWidth * rowNum + (rowNum - 1) * StatusPictureViewItemMargin
        let W = maxWidth
        
        

        
        return CGSize(width: W, height: H)
    }
}

// MARK: - 展现动画的协议
extension StatusCellPictureView: PhotoBrowserPresentDelegate {
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let v = UIImageView()
        v.contentMode = .ScaleAspectFill
        v.clipsToBounds = true
        
        // sd_webImage 如果已经存在本地缓存,不会发起网络请求
        if let url = ViewModel?.thumbnailUrls![indexPath.item] {
            
            v.sd_setImageWithURL(url)
        }


        
        return v
        
    }
    
    func photoBrowserPresonFromRect(indexPath: NSIndexPath) -> CGRect {
        let cell = self.cellForItemAtIndexPath(indexPath)!

        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)

        // 测试转换的Rect
//        let v = UIView(frame: rect)
//        v.backgroundColor = UIColor.redColor()
//      let v = imageViewForPresent(indexPath)
//        v.frame = rect
//
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        
        return rect
    }
    
    func photoBrowserPresonToRect(indexPath: NSIndexPath) -> CGRect {
        guard let key = ViewModel?.thumbnailUrls![indexPath.item].absoluteString else{
            return CGRectZero
        }
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        let screenHeight = UIScreen.mainScreen().bounds.height
        var y: CGFloat = 0
        
        if h < screenHeight {
            y = (screenHeight - h) * 0.5
        }
        
        let rect = CGRect(x: 0, y: y, width: w, height: h)
        
//        let v = imageViewForPresent(indexPath)
//        v.frame = rect
//        
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        return rect
    }
}
